import Mock from "mockjs";

// 模拟用户数据
let mockUserList = [];

// 初始化 10 条测试数据
for (let i = 0; i < 10; i++) {
  mockUserList.push({
    id: `USER${i + 1}`,
    name: Mock.Random.cname(),
    sex: Mock.Random.boolean() ? '男' : '女',
    phone: Mock.Random.string('number', 11),
    idcard: Mock.Random.id(),
    workaddress: Mock.Random.county(true),
    entrydate: Mock.Random.date('yyyy-MM-dd')
  });
}

// 1. 登录接口
Mock.mock(/\/api\/login\/user/, "post", (options) => {
  const { id, password } = JSON.parse(options.body);
  if (id === "admin" && password === "123456") {
    return {
      code: 200,
      data: {
        token: "mock-token",
        user: { id, name: "管理员", type: 0 }
      }
    };
  }
  return { code: 401, message: "登录失败" };
});

// 2. 用户列表接口（支持分页和搜索）
Mock.mock(/\/api\/user\/page\/admin/, "post", (options) => {
  const { keyword, page = 1, pageSize = 10 } = JSON.parse(options.body);
  
  // 搜索过滤
  let filteredList = mockUserList;
  if (keyword) {
    filteredList = filteredList.filter(item => 
      item.name.includes(keyword) || 
      item.id.includes(keyword) ||
      item.phone.includes(keyword)
    );
  }
  
  // 分页
  const start = (page - 1) * pageSize;
  const end = start + pageSize;
  
  return {
    code: 200,
    data: {
      total: filteredList.length,
      list: filteredList.slice(start, end)
    }
  };
});

// 3. 新增用户接口
Mock.mock(/\/api\/user\/add/, "post", (options) => {
  const newUser = JSON.parse(options.body);
  mockUserList.unshift(newUser); // 添加到列表头部
  return {
    code: 200,
    success: true,
    data: newUser,
    message: "用户添加成功"
  };
});

// 4. 编辑用户接口
Mock.mock(/\/api\/user\/edit/, "post", (options) => {
  const updatedUser = JSON.parse(options.body);
  const index = mockUserList.findIndex(item => item.id === updatedUser.id);
  
  if (index !== -1) {
    mockUserList[index] = updatedUser;
    return {
      code: 200,
      success: true,
      data: updatedUser,
      message: "用户更新成功"
    };
  }
  
  return {
    code: 404,
    success: false,
    message: "用户不存在"
  };
});

// 5. 删除用户接口
Mock.mock(/\/api\/user\/del\/(.*)/, "post", (options) => {
  const id = options.url.split('/').pop();
  const index = mockUserList.findIndex(item => item.id === id);
  
  if (index !== -1) {
    mockUserList.splice(index, 1);
    return {
      code: 200,
      success: true,
      message: "用户删除成功"
    };
  }
  
  return {
    code: 404,
    success: false,
    message: "用户不存在"
  };
});